package com.cai.security;

import com.alibaba.dubbo.config.annotation.Reference;
import com.cai.pojo.Permission;
import com.cai.pojo.Role;
import com.cai.pojo.User;
import com.cai.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Component
public class SpringSecurityUserService implements UserDetailsService {
    @Reference
    private UserService userService;

    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        //调用远程服务根据用户名查询数据库
        User user = userService.findUserByUsername(s);
        if(user==null){
            return null;
        }
        //创建用来添加权限的集合
        List<GrantedAuthority>list=new ArrayList<>();
        Set<Role> roles = user.getRoles();
        for (Role role : roles) {
            list.add(new SimpleGrantedAuthority(role.getKeyword()));//授予角色
            Set<Permission> permissions = role.getPermissions();//获取用户的权限
            for (Permission permission : permissions) {
                list.add(new SimpleGrantedAuthority(permission.getKeyword()));//授权
            }
        }
        return new org.springframework.security.core.userdetails.User(s,user.getPassword(),list);
    }
}
